package com.example.p2p;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.example.websocket.ImConfigConst;
import com.example.websocket.ImEnum;
import com.example.websocket.ImMessage;

import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.server.handler.IWsMsgHandler;


public class P2pServerWsMsgHandler implements IWsMsgHandler {
    private static final String TAG = "P2pServerAioHandler";

    /**
     * 握手时走这个方法，业务可以在这里获取cookie，request等
     * 对httpResponse参数进行补充并返回，如果返回null表示不想和对方建立连接
     * 对于大部分业务，该方法只需要一行代码：return httpResponse;
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) {
        String uid = httpRequest.getParam(ImConfigConst.UID);

        if (!hasText(uid)) {
            return null;
        }

        Log.d(TAG, String.format("P2P握手成功：用户ID：%s", uid));

        return httpResponse;
    }

    /**
     * 握手成功后触发该方法
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) {
        String uid = httpRequest.getParam(ImConfigConst.UID);

        Tio.closeUser(channelContext.tioConfig, uid, null);
        Tio.bindUser(channelContext, uid);

    }

    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) {
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) {
        Tio.remove(channelContext, "P2P连接关闭");
        return null;
    }

    public static String removeHtml(String content) {
        return content.replace("</", "《/")
                .replace("/>", "/》")
                .replace("<script", "《style")
                .replace("<style", "《style")
                .replace("<img", "《img")
                .replace("<br", "《br")
                .replace("<input", "《input");
    }

    public static boolean hasText(String str) {
        return str != null && !str.isEmpty() && containsText(str);
    }

    private static boolean containsText(CharSequence str) {
        int strLen = str.length();

        for(int i = 0; i < strLen; ++i) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }

        return false;
    }

    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) {
        if (!hasText(text)) {
            return null;
        }
        try {
            ImMessage imMessage = JSON.parseObject(text, ImMessage.class);

            String content = removeHtml(imMessage.getContent());
            if (!hasText(content)) {
                return null;
            }
            imMessage.setContent(content);

//            if (imMessage.getMessageType().intValue() == ImEnum.MESSAGE_TYPE_MSG_SINGLE.getCode()) {
//                sendSingleMsg(channelContext, imMessage);
//            }
        } catch (Exception e) {
            Log.e(TAG, "P2P解析消息失败", e);
        }
        //返回值是要发送给客户端的内容，一般都是返回null
        return null;
    }

    private void sendSingleMsg(ChannelContext channelContext, ImMessage imMessage) {
        sendSingleMsg(channelContext.tioConfig, imMessage);
    }

    public void sendSingleMsg(TioConfig tioConfig, ImMessage imMessage) {
        WsResponse wsResponse = WsResponse.fromText(JSON.toJSONString(imMessage), ImConfigConst.CHARSET);

        // 向目标发送消息
        Tio.sendToUser(tioConfig, imMessage.getToId().toString(), wsResponse);
    }

}
